package com.graducationdesign.springboot.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mr.zhneg
 * @create 2019-11-06-21:05
 * 定义登录拦截器
 * 所有访问都要经过这个拦截器
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {
    Logger logger = LoggerFactory.getLogger(getClass());

    //调用目标方法之前被拦截，比如maint/s/a.html进来，要拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws ServletException, IOException {

      Object loginuser= request.getSession().getAttribute("loginUser");
        String requestURI = request.getRequestURI();
        logger.info("preHandle拦截的请求路径是{}",requestURI);

        if(loginuser!=null){
          logger.info("有权限,登录。。。" );

          //已经登陆过放行
          return true;
      }

      //没有登陆过
        logger.info("没有权限请先登录。。。" );

        request.setAttribute("msg","没有权限请先登录，返回到管理员的登录界面");
        //返回到管理员的登录界面
      request.getRequestDispatcher("/indexa.html").forward(request,response);
      return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                    @Nullable ModelAndView modelAndView) throws Exception {
        logger.info("postHandle执行==================="+modelAndView);
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                 @Nullable Exception ex) throws Exception {
        logger.info("afterCompletion执行==================="+ex);

    }

}
